using System;
using System.Collections;
using UnityEngine;

public class NPC_Goner : MonoBehaviour
{
	[Header("-= Goner Info =-")]
	[SerializeField]
	private string GonerName = "name";

	[SerializeField]
	private AudioClip VanishSound;

	[SerializeField]
	private INT_Chat AccompanyingChatter;

	[SerializeField]
	private int RequiredFunValue = 66;

	public bool hasBeenInteracted;

	[Header("-= Glitch Effects =-")]
	[SerializeField]
	private Animator GlitchAnimator;

	[SerializeField]
	private SpriteRenderer[] GlitchEffects;

	[SerializeField]
	private float SizeVariation = 0.2f;

	[SerializeField]
	private float PositionVariation = 0.25f;

	[SerializeField]
	private int frameDelay = 15;

	private int currentFrame;

	private void Start()
	{
		if (Mathf.RoundToInt(PlayerPrefs.GetFloat("Setting_FunValue", -1f) * 100f) != RequiredFunValue)
		{
			base.gameObject.SetActive(value: false);
			return;
		}
		StartCoroutine(GlitchIdleLoop());
		ChatboxManager instance = ChatboxManager.Instance;
		instance.Event_OnTextEnd = (Action<CHATBOXTEXT>)Delegate.Combine(instance.Event_OnTextEnd, new Action<CHATBOXTEXT>(OnChatboxEndText));
	}

	private void Update()
	{
		if (AccompanyingChatter.CurrentlyBeingUsed)
		{
			hasBeenInteracted = true;
		}
		currentFrame++;
		if (currentFrame % frameDelay == 0)
		{
			SpriteRenderer[] glitchEffects = GlitchEffects;
			foreach (SpriteRenderer obj in glitchEffects)
			{
				float num = 0.5f + UnityEngine.Random.Range(0f - SizeVariation, SizeVariation);
				obj.transform.localScale = Vector3.one * num;
				Vector3 localPosition = new Vector3(UnityEngine.Random.Range(0f - PositionVariation, PositionVariation), UnityEngine.Random.Range(0f - PositionVariation, PositionVariation), 0f);
				obj.transform.localPosition = localPosition;
			}
		}
	}

	private IEnumerator GlitchIdleLoop()
	{
		yield return new WaitForSeconds(UnityEngine.Random.Range(5, 10));
		GlitchAnimator.Play($"Glitch_Bug{UnityEngine.Random.Range(1, 4)}");
		StartCoroutine(GlitchIdleLoop());
	}

	private void OnChatboxEndText(CHATBOXTEXT previousText)
	{
		if (hasBeenInteracted)
		{
			Vanish();
		}
	}

	private void Vanish()
	{
		ChatboxManager instance = ChatboxManager.Instance;
		instance.Event_OnTextEnd = (Action<CHATBOXTEXT>)Delegate.Remove(instance.Event_OnTextEnd, new Action<CHATBOXTEXT>(OnChatboxEndText));
		PlayerPrefs.SetInt("GONER_" + GonerName + "_USED", 1);
		CutsceneUtils.PlaySound(VanishSound);
		base.gameObject.SetActive(value: false);
		PlayerPrefs.SetFloat("Setting_FunValue", 0f);
	}

	private void OnDestroy()
	{
		ChatboxManager instance = ChatboxManager.Instance;
		instance.Event_OnTextEnd = (Action<CHATBOXTEXT>)Delegate.Remove(instance.Event_OnTextEnd, new Action<CHATBOXTEXT>(OnChatboxEndText));
	}
}
